var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 上传包铺贴凭证
    depositprictrueList: [],
    // 是否收到包铺贴金额
    switch1Checked: false,
    // 店长上传包铺贴金额
    price: "",
    // 店长上传封面图:
    coverList: [],
    // 店长上传合同:
    contractList: [],
    // 定金
    deposit: "",
    // 尾款
    payment: "",
    // 遮罩层
    issuccessMask: false,
    // 项目id
    orderId: "",
  },

  bindsunmit() {
    // if (this.data.contractList.length == 0) {
    //   wx.showToast({
    //     title: '请上传封面图',
    //     icon: "none"
    //   })
    //   return
    // }
    if (this.data.coverList.length == 0) {
      wx.showToast({
        title: '请上传包铺贴合同',
        duration: 2500, //持续的时间
            icon: 'none', //图标
      })
      return
    }
    if (this.data.price == '') {
      wx.showToast({
        title: '请填写包铺贴金额',
        duration: 2500, //持续的时间
        icon: 'none', //图标
      })
      return
    }
    if (this.data.deposit == '') {
      wx.showToast({
        title: '请填写包铺贴定金',
        duration: 2500, //持续的时间
        icon: 'none', //图标
      })
      return
    }
    if (this.data.deposit - 0 > this.data.price - 0) {
      wx.showToast({
        title: '包铺贴金额不能大于包铺贴定金',
        duration: 2500, //持续的时间
            icon: 'none', //图标
      })
      return
    }



    let orderObj = this.data.orderObj
    orderObj.price = this.data.price
    orderObj.projectCover = this.data.coverList
    orderObj.bptContract = this.data.contractList
    orderObj.bptDepositFlag = 1,
      orderObj.bptDeposit = this.data.deposit
    orderObj.bptBalance = this.data.payment
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2]; //prevPage 是获取上一个页面的js里面的pages的所有信息。 -2 是上一个页面，-3是上上个页面以此类推。\\
    prevPage.setData({
      orderObj: orderObj
    })
    wx.navigateBack({
      delta: 1,
    })




  },
  // 上传附件
  upload(arr) {
    // console.log(arr)
    let t = this
    return new Promise((reslove, reject) => {
      if (arr.length == 0) {
        reslove([])
        return
      }
      wx.showLoading({
        title: '上传中...', //提示的内容
        mask: true //显示透明蒙层 防止触摸穿透
      })
      let finishFilesList = []
      arr.forEach((item, index) => {
        wx.uploadFile({
          url: app.globalData.Interfaceurl + 'saveFileUpload',
          filePath: item,
          name: 'file',
          formData: {
            userId: app.globalData.userId,

          },
          header: {
            "content-type": "multipart/form-data"
          },
          success: function (res) {
            finishFilesList.push(JSON.parse(res.data).fileUrl)
            if (index >= arr.length - 1) {
              setTimeout(()=>{
                wx.hideLoading();
                reslove(finishFilesList)
               },500)
            }
          },
          fail: err => {
            return err
          }
        })
      })
    })


  },
  // 店长创建编辑项目
  saveProjectOrder() {
    let t = this
    wx.showLoading({
      title: '加载中',
    })
    // console.log("执行3")


    // wx.switchTab({
    //   url: '/pages/project/project',
    // })

    let bptContract=t.data.orderObj.bptContract.join(",")

    wx.request({
      url: app.globalData.Interfaceurl + 'saveProjectOrder',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        token: t.data.token,
        orderId: t.data.orderId,
        operateType: 1,
        designerId: t.data.orderObj.designerId,
        customerName: t.data.orderObj.customerName,
        customerPhone: t.data.orderObj.customerPhone,
        projectProvince: t.data.orderObj.projectProvince,
        projectCity: t.data.orderObj.projectCity,
        projectArea: t.data.orderObj.projectArea,
        projectAddress: t.data.orderObj.projectAddress,
        projectName: t.data.orderObj.projectName,
        projectSize: t.data.orderObj.projectSize,
        projectLayout: t.data.orderObj.projectLayout,
        projectCover: t.data.orderObj.projectCover.join(","),
        bptContract:bptContract ,
        bptAmount: t.data.orderObj.bptAmount,
        bptDepositFlag: t.data.orderObj.bptDepositFlag,
      },
      success: res => {
        wx.hideLoading()
        console.log(res)
        if (res.data.result == 0) {
          t.setData({
            issuccessMask: true
          })
        } else {
          wx.showToast({
            title: res.data.message,
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
          t.setData({
            token: app.token()
          })
        }
      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
      }
    })
  },
  // 修改产品型号
  modifyDesign() {
    wx.navigateTo({
      url: '/packageA/pages/productMap/productMap?from=modifyDesign',
    })
  },
  // 是否收到包铺贴金额
  switch1Change() {
    if (this.data.todo) {
      this.setData({
        switch1Checked: true
      })
    } else {
      this.setData({
        switch1Checked: !this.data.switch1Checked
      })
    }

  },
  // 店长点击保存
  seve() {
    // if (this.data.contractList.length == 0) {
    //   wx.showToast({
    //     title: '请上传封面图',
    //     icon: "none"
    //   })
    //   return
    // }
    if (this.data.contractList.length == 0) {
      wx.showToast({
        title: '请上传包铺贴合同',
        duration: 2500, //持续的时间
        icon: 'none', //图标
      })
      return
    }
    if (this.data.price == '') {
      wx.showToast({
        title: '请填写包铺贴金额',
        duration: 2500, //持续的时间
            icon: 'none', //图标
      })
      return
    }
    if (this.data.switch1Checked == true) {
    
      return
    }

    if (this.data.deposit != '') {
      if (this.data.deposit - 0 > this.data.price - 0) {
        wx.showToast({
          title: '包铺贴金额不能大于包铺贴定金',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
        return
      }
    }




    if (this.data.orderId == '') {
      let orderObj = this.data.orderObj
      this.upload(this.data.coverList)
        .then(res => {
          console.log("第一执行完", res)
          orderObj.projectCover = res
          this.upload(this.data.contractList)
            .then(res => {
              console.log("第二执行完", res)
              orderObj.bptAmount = this.data.price
              orderObj.bptDepositFlag = this.data.switch1Checked ? 1 : 0
              orderObj.bptContract = res
              orderObj.bptDeposit = this.data.deposit
              orderObj.bptBalance = this.data.payment
              this.setData({
                orderObj: orderObj
              })
          
              this.saveProjectOrder()
            })
        })
    } else {
      let orderObj = this.data.orderObj
      if (this.data.coverList.length != 0) {

        var newuncoverList = []
        var nocoverList = this.data.coverList.filter(item => item.indexOf(app.globalData.Imageurl) == -1)
        var uncoverList = this.data.coverList.filter(item => item.indexOf(app.globalData.Imageurl) != -1)
        uncoverList.forEach(item => {
          newuncoverList.push(item.replace(app.globalData.Imageurl, ""))
          item.replace(app.globalData.Imageurl, "")
        })
      } else {
        var nocoverList = []
        var newuncoverList = []
      }

      if (this.data.contractList.length != 0) {
        var nocontractList = this.data.contractList.filter(item => item.indexOf(app.globalData.Imageurl) == -1)
        var uncontractList = this.data.contractList.filter(item => item.indexOf(app.globalData.Imageurl) != -1)
        var newuncontractList = []
        uncontractList.forEach(item => {
          newuncontractList.push(item.replace(app.globalData.Imageurl, ""))
        })
      } else {
        var nocontractList = []
        var newuncontractList = []
      }





      this.upload(nocoverList)
        .then(res => {
          orderObj.projectCover = [...res, ...newuncoverList]
          this.upload(nocontractList)
            .then(res => {
              console.log("第二执行完", res)
              orderObj.bptAmount = this.data.price
              orderObj.bptDepositFlag = this.data.switch1Checked ? 1 : 0
              orderObj.bptContract = [...res, ...newuncontractList]
              orderObj.bptDeposit = this.data.deposit
              orderObj.bptBalance = this.data.payment
              this.setData({
                orderObj: orderObj
              })
              // console.log( orderObj.bptContract)
              // return
              this.saveProjectOrder()
            })
        })


      // orderObj.bptAmount = this.data.price
      // orderObj.bptDepositFlag = 0
      // this.setData({
      //   orderObj: orderObj,

      // })




      // 
      // .
      //   console.log("第一执行完", res)

      //   this.upload(this.data.contractList.map(item=>item.url))
      //     .then(res => {
      //       console.log("第二执行完", res)
      //       this.setData({
      //         bptContract: res
      //       })
      //       this.saveProjectOrder()
      //     })
      // })




      // this.saveProjectOrder()
    }
  },
  // 店长点击下一步事件
  goorderDetails() {
    if (this.data.switch1Checked) {
      // if (this.data.contractList.length == 0) {
      //   wx.showToast({
      //     title: '请上传封面图',
      //     icon: "none"
      //   })
      //   return
      // }
      if (this.data.contractList.length == 0) {
        wx.showToast({
          title: '请上传包铺贴合同',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
        return
      }
      if (this.data.price == '') {
        wx.showToast({
          title: '请填写包铺贴金额',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
        return
      }
      if (this.data.deposit == '') {
        wx.showToast({
          title: '请填写包铺贴定金',
          duration: 2500, //持续的时间
            icon: 'none', //图标
        })
        return
      }
      if (this.data.deposit - 0 > this.data.price - 0) {
        wx.showToast({
          title: '包铺贴金额不能大于包铺贴定金',
          duration: 2500, //持续的时间
            icon: 'none', //图标
        })
        return
      }

      if (this.data.switch1Checked==false) {
        wx.showToast({
          title: '请确定收到包铺贴后再点击下一步',
          duration: 2500, //持续的时间
            icon: 'none', //图标
        })
        return
      }

      let orderObj = this.data.orderObj
      orderObj.price = this.data.price
      orderObj.projectCover = this.data.coverList
      orderObj.bptContract = this.data.contractList
      orderObj.bptDepositFlag = 1,
        orderObj.bptDeposit = this.data.deposit,
        orderObj.bptBalance = this.data.payment,
        orderObj.orderId = this.data.orderId
      wx.navigateTo({
        url: '/shopowner/pages/depositAttachment/depositAttachment?orderObj=' + JSON.stringify(orderObj) + "&&depositprictrueList=" + JSON.stringify(this.data.depositprictrueList)
      })
    } else {
      wx.showToast({
        title: '请确认收到定金,再点击下一步',
        duration: 2500, //持续的时间
        icon: 'none', //图标
      })
    }

  },
  // 店长上传封面图事件
  Unplonecover(e) {
    this.setData({
      coverList: e.detail
    })

  },

  // 店长上传包铺贴合同
  Unplonecontract(e) {
    this.setData({
      contractList: e.detail
    })
  },

  // 失去铺贴金额焦点
  bindprice() {
    if (this.data.price == '') {
      this.setData({
        payment: 0
      })
      return
    }
    let price = this.data.price - 0
    let deposit = this.data.deposit
    this.setData({
      price: price.toFixed(2),

    })
    if (deposit == '') {
      this.setData({
        payment: this.data.price
      })
    } else {
      deposit = deposit - 0
      let payment = this.data.price - deposit.toFixed(2)
      if (payment < 0) {
        payment = 0
      }
      this.setData({
        payment: payment.toFixed(2)
      })
    }
  },
  // 定金失去焦点
  binddigit() {
    if (this.data.deposit == '') {
      this.setData({
        payment: 0
      })
      return
    }
    let deposit = this.data.deposit - 0
    let price = this.data.price
    this.setData({
      deposit: deposit.toFixed(2),

    })
    if (price == '') {
      this.setData({
        payment: 0
      })
    } else {
      price = price - 0
      let payment = price.toFixed(2) - this.data.deposit

      if (payment < 0) {
        payment = 0
      }
      this.setData({
        payment: payment.toFixed(2)
      })
    }
  },
  // 隐藏遮罩层
  HidesuccessMask() {
    this.setData({
      issuccessMask: false
    })
    app.globalData.tabindex = 1
    wx.setStorageSync('istab', true)
    wx.switchTab({
      url: '/pages/project/project',
    })
  },
  ndpayment() {
    if (this.data.payment == '') {
      return
    }
    let payment = this.data.payment - 0
    this.setData({
      payment: payment.toFixed(2),

    })
  },
  fakeCallback() {},
  // 项目详情
  getOrderDetails(orderId) {
    wx.request({
      url: app.globalData.Interfaceurl + 'getOrderDetails',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        orderId: orderId,
      },
      success: res => {
        console.log(res)
        let projectOrder = res.data.projectOrder
        let orderObj = {
          bptContract: projectOrder.bptContract.split(","),
          bptDepositFlag: projectOrder.bptDepositFlag,
          customerName: projectOrder.customerName,
          customerPhone: projectOrder.customerPhone,
          designerId: projectOrder.designerId,
          designerObj: res.data.designer,
          price: projectOrder.bptAmount,
          projectAddress: projectOrder.projectAddress,
          projectArea: projectOrder.projectArea,
          projectCover: projectOrder.projectCover.split(","),
          projectLayout: projectOrder.projectLayout,
          projectCity: projectOrder.projectCity,
          projectName: projectOrder.projectName,
          projectProvince: projectOrder.projectProvince,
          projectSize: projectOrder.projectSize,
          bptDepositFlag: projectOrder.bptDepositFlag,
          bptDeposit: projectOrder.bptDeposit,
          bptBalance: projectOrder.bptBalance,
        }
        // let contractList=orderObj.bptContract
        // let coverList=orderObj.projectCover
        let coverList = []
        if (orderObj.projectCover != '') {
          orderObj.projectCover.forEach(item => coverList.push(app.globalData.Imageurl + item))
        } else {
          orderObj.projectCover = coverList
        }
        let contractList = []
        orderObj.bptContract.forEach(item => contractList.push(app.globalData.Imageurl + item))


        this.setData({
          orderObj: orderObj,
          price: orderObj.price,
          coverList: coverList,
          contractList: contractList,
          switch1Checked: projectOrder.bptDepositFlag == 1 ? true : false,
          deposit: projectOrder.bptDeposit,
          payment: projectOrder.bptBalance
        })
      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
            icon: 'none', //图标
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    this.setData({
      token: app.token(),
      identity:app.globalData.identity
    })
    if (options.orderObj) {
      this.setData({
        orderObj: JSON.parse(options.orderObj)
      })

    }
    if (options.todo) {
      this.setData({
        todo: options.todo
      })
    }

    if (options.id) {
      this.setData({
        orderId: options.id
      })
      this.getOrderDetails(options.id)


    }


    // 订单修改
    if (options.todo == 'modifyOrder') {
      this.setData({
        coverList: this.data.orderObj.projectCover,
        contractList: this.data.orderObj.bptContract,
        price: this.data.orderObj.price,
        deposit: this.data.orderObj.bptDeposit,
        payment: this.data.orderObj.bptBalance,
        switch1Checked: true,
        depositprictrueList: this.data.orderObj.bptDepositProof
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})